<template>
  <div class="session-detail">
    <div class="detail-header">
      <div class="header-left">
        <h2 class="detail-title">{{ session.topic }}</h2>
        <div class="detail-meta">
          <span class="detail-time">{{ formatDate(session.created_at) }}</span>
          
          <div v-if="type === 'debate'" class="detail-positions">
            <el-tag 
              :type="debateSession.position === 'pro' ? 'success' : 'danger'"
              effect="light"
              size="small"
            >
              {{ debateSession.position === 'pro' ? '正方' : '反方' }} (你)
            </el-tag>
            <el-tag 
              :type="debateSession.position === 'pro' ? 'danger' : 'success'"
              effect="light"
              size="small"
            >
              {{ debateSession.position === 'pro' ? '反方' : '正方' }} (AI)
            </el-tag>
          </div>

          <div v-else class="detail-training-type">
            <el-tag type="info" effect="light" size="small">
              {{ trainingSession.trainingType }}
            </el-tag>
          </div>
        </div>
      </div>
      
      <div class="header-right">
        <el-button @click="$emit('close')" text icon="Close" />
      </div>
    </div>

    <div v-if="type === 'debate' && debateSession.result" class="detail-result">
      <el-alert
        :title="`辩论结果: ${debateSession.result}`"
        :type="getResultType(debateSession.result)"
        :closable="false"
        show-icon
      />
    </div>

    <div class="message-container" ref="messageContainer">
      <div v-if="isLoading" class="loading-messages">
        <el-skeleton :rows="6" animated />
      </div>

      <template v-else-if="messages.length > 0">
        <div v-for="(message, index) in messages" :key="index" class="message" :class="`message-${message.role}`">
          <div class="message-avatar">
            <el-avatar :size="40" :icon="message.speaker === 'user' ? 'User' : 'ChatLineRound'" />
          </div>
          <div class="message-content">
            <div class="message-header">
              <span class="message-sender">{{ message.speaker === 'user' ? '你' : 'AI助手' }}</span>
              <span class="message-time">{{ formatMessageTime(message.timestamp) }}</span>
            </div>
            <div class="message-body" v-html="renderMessageContent(message.content)"></div>
          </div>
        </div>
      </template>

      <el-empty v-else description="暂无对话记录" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, PropType, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { marked } from 'marked'
import hljs from 'highlight.js'
import { getSessionMessages } from '../services/debateServ'
import type { Session, TrainingSession, ChatMessage } from '../models/debate'


// Props 定义
const props = defineProps({
  session: {
    type: Object as PropType<Session | TrainingSession>,
    required: true
  },
  type: {
    type: String as PropType<'debate' | 'training'>,
    required: true
  }
})

// 向父组件发送关闭事件
defineEmits(['close'])

// 会话类型转换
const debateSession = computed(() => props.session as Session)
const trainingSession = computed(() => props.session as TrainingSession)

// 消息列表
const messages = ref<ChatMessage[]>([])
const isLoading = ref(true)
const messageContainer = ref<HTMLElement | null>(null)

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化消息时间
const formatMessageTime = (timestamp: string) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取结果类型
const getResultType = (result: string) => {
  if (result.includes('胜')) return 'success'
  if (result.includes('败')) return 'error'
  return 'warning'
}

// 渲染消息内容（支持 Markdown）
const renderMessageContent = (content: string) => {
  return marked(content)
}

// 加载消息
const loadMessages = async () => {
  isLoading.value = true
  
  try {
    const response = await getSessionMessages(props.session.id)
    messages.value = response.data
    console.log('Loaded messages:', response.data)
    console.log('Loaded messages:', messages.value)
    
    // 加载完成后滚动到底部
    await nextTick()
    scrollToBottom()
  } catch (error) {
    ElMessage.error('加载对话记录失败')
    console.error('Failed to load messages:', error)
  } finally {
    isLoading.value = false
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight
  }
}

// 初始化
onMounted(async () => {
  await loadMessages()
})
</script>

<style scoped>
.session-detail {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.header-left {
  flex: 1;
}

.detail-title {
  margin: 0 0 10px 0;
  font-size: 1.5rem;
  color: #303133;
}

.detail-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  color: #909399;
  font-size: 14px;
}

.detail-positions, .detail-training-type {
  display: flex;
  gap: 8px;
}

.detail-result {
  margin-bottom: 20px;
}

.message-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.loading-messages {
  padding: 20px;
}

.message {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.message-user {
  flex-direction: row-reverse;
}

.message-content {
  background-color: #f4f4f5;
  border-radius: 8px;
  padding: 12px 16px;
  max-width: 80%;
}

.message-user .message-content {
  background-color: #ecf5ff;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.message-sender {
  font-weight: 500;
  color: #303133;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-body {
  color: #606266;
  line-height: 1.6;
}

/* Markdown 样式 */
:deep(pre) {
  background-color: #f8f8f8;
  border-radius: 4px;
  padding: 12px;
  overflow-x: auto;
}

:deep(code) {
  font-family: monospace;
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 3px;
}

:deep(pre code) {
  background-color: transparent;
  padding: 0;
}

:deep(blockquote) {
  border-left: 4px solid #dfe2e5;
  padding-left: 16px;
  margin-left: 0;
  color: #6a737d;
}

:deep(img) {
  max-width: 100%;
}

:deep(table) {
  border-collapse: collapse;
  width: 100%;
}

:deep(th), :deep(td) {
  border: 1px solid #dfe2e5;
  padding: 8px 12px;
}

:deep(th) {
  background-color: #f6f8fa;
}
</style>